<template>
    <div class="app-container">
      <!-- Header Section -->
      <header class="header">
        <div>
          <div class="header-title">{{bigModelName}}</div>
          <div class="header-subtitle">{{bigModelDEsc}}</div>
        </div>
        <div>
          <el-button style="position: absolute;right: 0;top: 50%;transform: translate(0,-50%);" type="primary" @click="backHome()">返回首页</el-button>
        </div>
      </header>
      
      <main class="main">
        <div class="main-top">
  <div class="top-left">
    <div class="image-container">
      <!-- Show image when uploadedImageUrl exists -->
      <div v-if="uploadedImageUrl"   v-loading="seImage" class="image-wrapper">
        <el-image
          :src="uploadedImageUrl"
          style="width: 100%; height: 100%"
          fit="contain"
        />
        <canvas ref="canvasRef" class="bounding-box-canvas"></canvas>
        <el-button 
          class="delete-image-btn" 
          type="danger" 
          :icon="Delete" 
          circle 
          @click="handleRemoveImage"
        />
      </div>
      
      <!-- Show upload placeholder when no image -->
      <div v-else class="upload-placeholder">
        <el-upload
          class="custom-upload"
          drag
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleImageChange"
          accept="image/*"
        >
          <div class="upload-content">
            <img class="upload-icon" src="../assets/image/upload.png" alt="" >
            <div class="upload-text">
              <p class="main-text">点击或拖拽图片到此处</p>
              <p class="sub-text">支持 PNG、JPG、JPEG、BMP 格式</p>
            </div>
          </div>
        </el-upload>
      </div>
    </div>
  </div>
          
          <div class="top-right">
            <div class="result-header">
              识别结果
            </div>
            <div class="result-content">
              <div v-if="isProcessing" class="processing-message">
                解析中...
              </div>
              <div v-else-if="!algorithmResultMessageList" class="empty-result">
                请输入并发送提示词查看检测结果
              </div>
              <div v-else-if="algorithmResultMessageList == 0" class="empty-result">
                未识别目标结果
              </div>
              <div v-else class="result-items">
                <table style="width: 100%; border-collapse: collapse;">
         <thead>
          <tr>
            <th style="text-align: center;color: black;">序号</th>
            <th style="text-align: center;color: black;">标签</th>
            <th style="text-align: center;color: black;">置信度</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in algorithmResultMessageList" :key="item.id" style="border: none;">
            <td style="padding-top: 10px;text-align: center;color: black;">{{ item.id }}</td>
            <td style="padding-top: 10px;text-align: center;color: black;">{{ item.code }}</td>
            <td style="padding-top: 10px;text-align: center;color: black;">{{ (item.confidence*100).toFixed(1) }}%</td>
          </tr>
        </tbody>
      </table>
              </div>
            </div>
          </div>
        </div>
        
        <!-- Bottom Section - Prompt Input -->
        <div class="main-bottom">
          <div class="bottom-left">
              <div style="font-size: 18px;color: white;margin-bottom: 20px;">检测提示词</div>
              <el-input
                v-model="promptText"
                placeholder="请输入英文提示词"
                clearable
                @keyup.enter="submitPrompt"
              />
              <el-button style="margin-top: 20px;width: 100%;" type="primary" @click="submitPrompt"     :disabled="!isSendButtonEnabled">发送</el-button>
          </div>
          <div class="bottom-right">
              <!-- 这里是触摸more显示出来的所有选项 -->
              <div v-if="checkAlgorithm" @mouseenter="checkAlgorithm = true" @mouseleave="checkAlgorithm = false" 
                  style="width: 80%;position: absolute;background-color:#0c294c;z-index: 999;bottom:70%;left: 10%;padding: 10px;max-width: 60vh;">
                <div
                  v-for="item in formattedMenuItems"
                  :key="item.id"
                  :id="item.href.slice(1)"
                  class="menu-item"
                >
              <!-- 场景标题和描述 -->
                <div class="scene-title" style="cursor: default;">
                  {{ item.name }}
                </div>
              <!-- 算法展示网格 -->
                <div class="algorithm-grid">
                <div
                  v-for="algorithm in item.algorithms"
                  :key="algorithm.id"
                  class="algorithm-item"
                >
                    <span type="primary"  class="algorithm-name" @click="changeAlgor(algorithm)" style="cursor: pointer;">{{ algorithm.name }}</span>
                 </div>
              </div>
              </div>
              </div>

              <div class="bottom-right-left"> 
                <img style="width: 60%;height: auto;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);" src="../assets//image/algorith.png" alt="">
              </div>
              <div class="bottom-right-middle">
                <div style="width: 100%; position: absolute;top: 50%;left: 50%;transform:translate(-50%,-50%);">
                  <div style="display: flex;">
                    <img src="../assets//image/al.png"  style="width: 1rem;height: auto;"  alt="">
                    <div style="font-size:1rem;margin-left: 0.5rem;">{{scenarioName}}</div> 
                  </div>
                <div style="font-size:1.2rem;">{{bigModelName}}</div>
                </div>
              </div>
              <div class="bottom-right-right" @mouseenter="checkAlgorithm = true" @mouseleave="checkAlgorithm = false"  @click="checkAlgorithm = true">
                <div style="position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);">
                    <div class="moreChange" style="font-size: 2.3rem; cursor: pointer;">more</div>
                </div>
              </div> 
          </div>
        </div>
      </main>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref ,onMounted , computed , nextTick} from 'vue'
  import { useRouter, useRoute} from 'vue-router'
  import { Delete } from '@element-plus/icons-vue'
  import { ElMessage , type UploadFile } from 'element-plus'
  import request from '@/utils/request'
import { fa } from 'element-plus/es/locales.mjs'
  const seImage = ref(false)
  const router = useRouter()
  const route = useRoute()
//   这里接受这三个值，id，名称以及，描述
  const bigModelId = ref()
  const bigModelName = ref()
  const bigModelDEsc = ref()
  const scenarioName = ref()

// 切换算法的弹窗
const checkAlgorithm =ref(false);//切换算法的弹窗

const formattedMenuItems = computed(() => {
    return AllAlgorithmAndAlgorithmScenario.value?.map((item: any, index: number) => ({
      id: item.scenario.id || "N/A",
      name: item.scenario.scenarioName || "未知场景",
      description: item.scenario.scenarioDescription || "无描述",
      href: `#part${index}`,
      algorithms: item.algorithms.map((algorithm: any) => ({
      id: algorithm?.algorithm?.id || "N/A", // 防止 undefined
      scenarioID: algorithm?.algorithm?.scenarioID || "N/A", // 防止 undefined
      name: algorithm?.algorithm?.algorithmName || "未知算法", // 防止 undefined
      coverUrl: algorithm?.algorithm?.coverUrl || "", // 防止 undefined
      algorithmResult:algorithm?.algorithm?.algorithmResult || "",//防止undefined
      description: algorithm?.algorithm?.description || "无描述", // 防止 undefined
      exampleUrl:algorithm?.algorithm?.exampleUrl || "", // 防止 undefined
      images:algorithm?.images || [],
    })),
  }))||[];
});

const AllAlgorithmAndAlgorithmScenario = ref()
const bigModel = ref()
const getAllAlgorithm = () => {
  request.get("/algorithm/algorithmView").then((res) => {   
    AllAlgorithmAndAlgorithmScenario.value = res.data.algorithmViews
    bigModel.value = res.data.largeModel

  });
};
const algorithmResult = ref([])//接收路由的算法坐标值
const algorithmResultMessageList = ref<any>()//算法返回的结果执信度
const changeAlgor = (item: any) => {
    // 逻辑与点击左侧按钮跳转到算法详情页面一样
    const result = JSON.stringify(item.algorithmResult);
    router.push({
      path: "/algorithmsMessage",
      query: {
        result: result,
        scenarioID: item.id,
        exampleUrl: item.exampleUrl,
      },
    });
};

// 清理canvas相关数据
const canvasRef = ref<HTMLCanvasElement | null>(null);
const clearCanvas = () => {
  const canvas = canvasRef.value;
  if (!canvas) return;

  const ctx = canvas.getContext("2d");
  if (ctx) {
    const { width, height } = canvas;
    ctx.clearRect(0, 0, width, height);
    canvas.width = width;
    canvas.height = height;
  }
};

const drawBoxes = async () => {
  clearCanvas();
  await nextTick();

  const canvas = canvasRef.value;
  const imgElement = canvas?.closest(".image-container")?.querySelector("img");
  if (!canvas || !imgElement) return;

  // 获取图片自然尺寸和容器尺寸
  const { naturalWidth, naturalHeight } = imgElement;
  const container = imgElement.parentElement;
  const containerRect = container?.getBoundingClientRect() || { width: 0, height: 0 };

  // 设置Canvas尺寸（高度100%，宽度按比例）
  canvas.style.height = "100%";
  canvas.style.width = `${(naturalWidth / naturalHeight) * containerRect.height}px`;
  canvas.style.left = `${(containerRect.width - parseFloat(canvas.style.width)) / 2}px`;
  canvas.style.top = "0";

  // 同步Canvas的像素尺寸（避免模糊）
  const computedStyle = getComputedStyle(canvas);
  canvas.width = parseFloat(computedStyle.width);
  canvas.height = parseFloat(computedStyle.height);

  const ctx = canvas.getContext("2d");
  if (!ctx) return;

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 计算实际绘制比例（考虑图片object-fit: contain的缩放）
  const imgRect = imgElement.getBoundingClientRect();
  const scaleX = imgRect.width / naturalWidth;
  const scaleY = imgRect.height / naturalHeight;
  const effectiveScale = Math.min(scaleX, scaleY);

  // 计算图片在Canvas中的偏移量（居中显示时）
  const imgRenderWidth = naturalWidth * effectiveScale;
  const imgRenderHeight = naturalHeight * effectiveScale;
  const offsetX = (canvas.width - imgRenderWidth) / 2;
  const offsetY = (canvas.height - imgRenderHeight) / 2;

  // 绘制边界框（坐标转换到Canvas空间）
  algorithmResult.value.forEach(({ x, y, x2, y2, id }) => {
    const boxX = offsetX + x * effectiveScale;
    const boxY = offsetY + y * effectiveScale;
    const boxWidth = (x2 - x) * effectiveScale;
    const boxHeight = (y2 - y) * effectiveScale;

    ctx.strokeStyle = "red";
    ctx.lineWidth = 2;
    ctx.strokeRect(boxX, boxY, boxWidth, boxHeight);

    ctx.fillStyle = "red";
    ctx.font = "14px Arial";
    ctx.fillText(`${id}`, boxX + 5, boxY + 15);
  });
};
  // Image upload
  const uploadedImageUrl = ref('')
  const fileListCoverImg = ref<UploadFile[]>([]);//新建，封面
  const isProcessing = ref(false)
  // 上传图片
  const handleImageChange = (file:any) => {
    // Validate file
    const isLt4M = file.size / 1024 / 1024 < 10
  
    
    if (!isLt4M) {
      ElMessage.error('图片大小不能超过 10MB!')
      return false
    }
    
    // Display the image
    uploadedImageUrl.value = URL.createObjectURL(file.raw)

    fileListCoverImg.value = [file]
    return true
  }
  // 删除图片按钮
  const handleRemoveImage = () => {
  uploadedImageUrl.value = ''
  promptText.value = ''
  algorithmResultMessageList.value = ''
}
  
  //发送按钮逻辑以及校验
  const promptText = ref('')
  const promptResult = ref('')


  const isSendButtonEnabled = computed(() => {
  return promptText.value.trim() !== '' && uploadedImageUrl.value !== ''
})
  
const submitPrompt = () => {
  seImage.value = true
  if (!promptText.value.trim()) {
    ElMessage.warning('请输入提示词')
    return
  }

  if (!fileListCoverImg.value || fileListCoverImg.value.length === 0) {
    ElMessage.warning('请先上传图片')
    return
  }

  isProcessing.value = true
  const formData = new FormData()
  formData.append('cueWord', promptText.value)

  fileListCoverImg.value.forEach((file) => {
    if (file.raw instanceof Blob) {
      formData.append('inputFile', file.raw)
    } else {
      console.warn('File does not have raw data:', file)
    }
  })

  request.post('/algorithm/modelAnalysis', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => {
    seImage.value = false
    promptResult.value = response.data.result
    algorithmResult.value = response.data.result
    algorithmResultMessageList.value = response.data.result
    drawBoxes();
  }).catch(error => {
    ElMessage.error('提交失败: ' + error.message)
    seImage.value = false
  }).finally(() => {
    isProcessing.value = false
    seImage.value = false
  })
}
  
  const backHome = () => {
    router.push('/')
  }
  onMounted(()=>{
    if (route.query.scenarioID) {
        bigModelId.value = route.query.scenarioID
        bigModelName.value =  route.query.name
        bigModelDEsc.value = route.query.description
        scenarioName.value = route.query.scenarioName
    }

    getAllAlgorithm()
  })

  </script>
  
  <style scoped>
  .app-container {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
  }
  
  .header {
    width: 100%;
    height: 10%;
    color: white;
    display: flex;
    position: relative;
  }
  
  .header-title {
    font-size: 1rem;
    font-weight: bold;
    margin-top: 5px;
  }
  
  .header-subtitle {
    font-size: 1em;
    margin-bottom: 5px;
    margin-top: 10px;
  }
  
  .main {
    width: 100%;
    height: 80%;
    overflow: visible;
  }
  
  .main-top {
    width: 100%;
    height: 70%;
    display: flex;
    margin-bottom: 20px;
  }
  
  .top-left {
    height: 100%;
    width: 70%;
    background-color: #fff;
    border-radius: 8px;
    margin-right: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    position: relative;
  }

  .image-container {
  width: 100%;
  height: 100%;
  background-color: black;
  position: relative;
  overflow: hidden; /* 防止滚动条 */
}

.image-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.bounding-box-canvas {
  position: absolute;
  height: 100%;
  top: 0;
  pointer-events: none;
  z-index: 2;
  background-color: transparent;
}

/* 确保图片保持比例 */
.image-wrapper .el-image {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
  object-fit: contain;
}

.delete-image-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 3; /* 删除按钮在最上层 */
}


  .delete-image-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 100;
  }
  
  .top-right {
    height: 100%;
    width: 30%;
    background-color: #fff;
    border-radius: 8px;
    margin-left: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
  }
  
  .result-header {
    color: #333;
    font-size: 1.3rem;
    font-weight: bold;
    padding: 15px;
    border-bottom: 1px solid #eee;
    text-align: center;
  }
  
  .result-content {
    flex: 1;
    padding: 15px;
    overflow-y: auto;
  }
  
  .processing-message {
    color: #409eff;
    text-align: center;
    margin-top: 20px;
    font-size: 1.1rem;
  }
  
  .empty-result {
    color: #67c23a;
    text-align: center;
    margin-top: 20px;
    font-size: 1.1rem;
  }
  
  .result-items {
    color: #333;
  }
  
  .main-bottom {
    width: 100%;
    height: 30%;
    display: flex;
    box-sizing: border-box;
  }
  
  .bottom-left {
    height: 100%;
    width: 70%;
    background-color: #ffffff3e;
    border-radius: 8px;
    margin-right: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    padding: 15px;
    box-sizing: border-box;
  }
  
  .bottom-right {
    height: 100%;
    width: 30%;
    background-color: #fff;
    border-radius: 8px;
    margin-left: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    position: relative;
  }
  
  .scene-title {
  font-size: 1rem;
  margin: 0.5rem 0;
  color: lightblue;
  font-weight: bold;
}
.algorithm-grid {
  padding: 7px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
/* 样式：单个算法项 */
.algorithm-item {
  flex: 0 0 32%;
  overflow: hidden;
}

/* 样式：算法名称 */
.algorithm-name {
  color: white;
  font-weight: bold;
  font-size: 0.9rem;

}
.algorithm-name:hover {
  color: skyblue;
}

  .bottom-right-left {
    flex: 1;
    height: 100%;
    position: relative;
  }
  .bottom-right-middle {
    flex: 1;
    height: 100%;
    position: relative;
    
  }
  .bottom-right-right {
    flex: 1;
    height: 100%;
    position: relative;
  }
  .demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
/* 选中颜色的函数 */
.box {
  box-sizing: border-box;
  z-index: 1; /* 确保边框不被覆盖 */
}
.selected {
  border: 2px solid #00bfff;
  border-color: #00bfff; /* 更改选中框的边框颜色 */
}

.textChangeColor {
  color: black;
}

.textChangeColor:hover {
  color: skyblue;
}

.moreChange {
  color:#0c294c;
}
.moreChange:hover {
  color: skyblue;
}

  .prompt-actions {
    display: flex;
    justify-content: flex-end;
  }
  
  .upload-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  :deep(.el-upload-dragger) {
    width: 400px;
    height: 200px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  
  :deep(.el-upload__text) {
    margin: 15px 0;
    font-size: 1rem;
  }
  
  :deep(.el-upload__tip) {
    color: #999;
    font-size: 0.8rem;
  }


  .custom-upload {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.custom-upload .el-upload) {
  width: 100%;
  height: 100%;
}

:deep(.custom-upload .el-upload-dragger) {
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  box-shadow: none;
}

:deep(.custom-upload .el-upload-dragger:hover) {
  border: none;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.upload-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 16px;
}

.upload-text {
  color: #606266;
}

.main-text {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.sub-text {
  font-size: 12px;
  color: #909399;
}

/* Remove focus outline */
:deep(.custom-upload .el-upload-dragger:focus) {
  outline: none;
}
  </style>